package org.common.utils.generatortable.data;

import com.alibaba.fastjson2.JSONObject;
import org.apache.commons.io.FileUtils;
import org.common.utils.generatortable.data.entity.DataEntity;
import org.common.utils.tool.StringTool;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.IOException;

public class DataManager {

    private static final Logger log = LoggerFactory.getLogger(DataManager.class);

    /**
     * 参数配置文件地址
     */
    private static final File FILE_ADDRESS = new File("generator-table-config.json");

    private DataEntity dataEntity = new DataEntity();

    public DataEntity getDataEntity() {
        return dataEntity;
    }

    /**
     * 保存配置
     */
    public void save() {
        try {
            log.info("save before {}" , JSONObject.toJSONString(dataEntity));
            FileUtils.write(FILE_ADDRESS , JSONObject.toJSONString(dataEntity), "utf-8");
        } catch (IOException ex) {
            throw new RuntimeException(ex);
        }
    }

    /**
     * 读取配置
     * @return
     */
    private DataEntity read() {
        try {
            if(!FILE_ADDRESS.exists())
                return null;
            String content = FileUtils.readFileToString(FILE_ADDRESS, "utf-8");
            if(StringTool.isEmpty(content))
                return null;
            return JSONObject.parseObject(content , DataEntity.class);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public void initBefore() {
        dataEntity = read();
        if(dataEntity == null)
            dataEntity = new DataEntity();
    }
}
